require 'rubygems'
require 'mechanize'

class MyspaceAgent
  attr_reader :agent
  attr_writer :agent

  def initialize
    # Create the agent
    @agent = WWW::Mechanize.new
  end

  def login(email, password)
    # Get the front page
    page = @agent.get('http://www.myspace.com')

    # Fill out the login form
    login_form          = page.forms.with.name('theForm').first
    login_form.email    = email
    login_form.password = password

    # Submit
    done = @agent.submit(login_form)
    succ = done.at('#home_profileInfo') ? true : false
    return succ
  end

  def get_profile(url = nil)
    # Get the profile page
    unless url
      page = @agent.get('http://home.myspace.com/index.cfm?fuseaction=user')
      url  = page.at('#home_userURLInfo center').children[10].to_s.strip
    end
    page    = @agent.get(url)
    profile = {:url => url}

    # Extract the info
    profile[:friend_id] = page.at('#ctl00_Main_ctl00_UserBasicInformation1_hlDefaultImage')['href'].match(/friendID=([0-9]+)/)[1].to_i
    profile[:image_url] = page.at('#ctl00_Main_ctl00_UserBasicInformation1_hlDefaultImage img')['src']
    profile[:name]      = page.at('table.profileInfo tr td span.nametext').inner_html
    profile[:tagline]   = page.at('#Table2 tr td[2]').children[0].to_s.strip
    profile[:sex]       = page.at('#Table2 tr td[2]').children[4].to_s.strip
    profile[:age]       = page.at('#Table2 tr td[2]').children[6].to_s.strip
    profile[:state]     = page.at('#Table2 tr td[2]').children[8].to_s.strip
    profile[:country]   = page.at('#Table2 tr td[2]').children[10].to_s.strip

    # Done
    return profile
  end

  def post_bulletin(subject, body)
    # Get the bulletin page
    home_page = @agent.get('http://home.myspace.com/index.cfm?fuseaction=user')
    bull_link = home_page.links.with.text('post bulletin').first
    bull_page = @agent.click(bull_link)

    # Fill out the bulletin form
    bull_form         = bull_page.forms.with.name('bulletinForm').first
    bull_form.body    = body
    bull_form.subject = subject

    # Submit the form, yeilding the confirmation page
    conf_page        = @agent.submit(bull_form)
    conf_form        = conf_page.forms.with.name('bulletinForm').first
    conf_form.action = conf_page.body.match(/document.bulletinForm.action='(.+?)'/)[1]
    
    # Submit
    done = @agent.submit(conf_form)
    succ = done.body.match(/Bulletin Has Been Posted/) ? true : false
    return succ
  end

  def edit_profile(section, &block)
    # Get the profile page
    edit_page = @agent.get('http://profileedit.myspace.com/index.cfm?fuseaction=profile.interests')
    edit_form = edit_page.forms.with.name('aspnetForm').first

    # Get the section
    mapping = {
               :about_me     => 'ctl00$ctl00$Main$ProfileEditContent$editInterests$AboutMeTextBox',
               :like_to_meet => 'ctl00$ctl00$Main$ProfileEditContent$editInterests$LikeToMeetText',
               :interests    => 'ctl00$ctl00$Main$ProfileEditContent$editInterests$GeneralText',
               :music        => 'ctl00$ctl00$Main$ProfileEditContent$editInterests$MusicText',
               :films        => 'ctl00$ctl00$Main$ProfileEditContent$editInterests$MoviesText',
               :television   => 'ctl00$ctl00$Main$ProfileEditContent$editInterests$TelevisionText',
               :books        => 'ctl00$ctl00$Main$ProfileEditContent$editInterests$BooksText',
               :heroes       => 'ctl00$ctl00$Main$ProfileEditContent$editInterests$HeroesText'
              }
    input_name = mapping[section]
    edit_form[input_name] = block.call(edit_form[input_name])

    # Submit
    done = @agent.submit(edit_form, edit_form.buttons.first)
    succ = (done.at('#ctl00_ctl00_Main_ProfileEditContent_editInterests_output').inner_html =~ /^Profile Updated/) ? true : false
    return succ
  end

  def add_friend(login)
    # Get the profile page
    page = @agent.get("http://www.myspace.com/#{login}")
    link = page.at('#ctl00_Main_ctl00_UserContactLinks1_AddFriendLink')['href']

    # Add to friends, yeilding the confirmation page
    conf_page = @agent.get(link)
    conf_form = conf_page.forms.with.name('addFriend').first

    # Submit
    done = @agent.submit(conf_form)
    succ = done.body.match(/An email has been sent to the user/) ? true : false
    return succ
  end
end
